/**
 * All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
 * <p>
 * MmsProvinceCityMatchinfoService
 * 省份地市信息表新
 * <p>
 * 修改纪录
 * 2022-01-10 版本：1.0 wangjielei 创建。
 *
 * @version 版本：1.0
 * @author 作者：wangjielei
 * 创建日期：2022-01-10
 */
package com.topscomm.mms.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.model.TreeModel;
import com.topscomm.mms.MmsSystemConst;
import com.topscomm.mms.pojo.MmsDeptProvinceCityMatchInfoEntity;
import com.topscomm.mms.pojo.PmsProvinceCityMatchInstanceEntity;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.service.impl.CboSysParamService;
import com.topscomm.mms.MmsSystemConst.AreaLevelEnum;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.mms.pojo.MmsProvinceCityMatchinfoEntity;
import com.topscomm.mms.service.IMmsProvinceCityMatchinfoService;
import com.topscomm.mms.service.impl.auto.MmsProvinceCityMatchinfoServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

@Service(value = "mmsProvinceCityMatchinfoService")
@Scope(value = "singleton")
public class MmsProvinceCityMatchinfoService extends MmsProvinceCityMatchinfoServiceAuto implements IMmsProvinceCityMatchinfoService {
    @Autowired
    private DatacodeCache datacodeCache;
    @Autowired
    private MmsProvinceCityMatchinfoService mmsProvinceCityMatchinfoService;
    @Autowired
    private MmsDeptProvinceCityMatchInfoService mmsDeptProvinceCityMatchInfoService;
    @Autowired
    private MmsDeptExtraInfoService mmsDeptExtraInfoService;
    @Autowired
    private CboSysParamService cboSysParamService;
    @Autowired
    private PmsProvinceCityMatchInstanceService pmsProvinceCityMatchInstanceService;
    //不足6位补0
    protected static String[] codes = {"", "0", "00", "000", "0000", "00000"};
    //编码长度
    public static int codeLen = 6;
    //编码长度
    public static int levelCodelen = 3;
    //初始编号
    public static String firstCode = "000001";
    //初始编号
    public static String firstLevelCode = "001";

    /**
     * @param mapRow
     * @author: hudeyong
     * @date: 2021-06-16
     * @description:设置字段显示值
     * @modify:
     */
    @Override
    public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
        super.setDispFields(mapRow, datacodeCache);
        String temp;
        if (mapRow.get("areatype") != null) {
            temp = mapRow.get("areatype").toString();
            mapRow.put("dispareatype", datacodeCache.getValueDynamic("AreaType", temp, "code", "name"));
        }
        if (mapRow.get("deptcommoncode") != null) {
            temp = mapRow.get("deptcommoncode").toString();
            mapRow.put("dispdeptcommoncode", datacodeCache.getValueDynamic("DeptCommonCodeTrack", temp, "code", "name"));
        }
        if (mapRow.get("namecode") != null) {
            temp = mapRow.get("namecode").toString();
            mapRow.put("dispnamecode", datacodeCache.getValueDynamic("DeptCommonCode2", temp, "code", "name"));
        }
        if (mapRow.get("arealevel") != null) {
            temp = mapRow.get("arealevel").toString();
            mapRow.put("disparealevel", datacodeCache.getValueDynamic("AreaLevel", temp, "code", "name"));
        }
        if (mapRow.get("areaauthorizationusercode") != null) {
            temp = mapRow.get("areaauthorizationusercode").toString();
            mapRow.put("dispareaauthorizationusercode", datacodeCache.getValueDynamic("CboUser", temp, "code", "name"));
        }
        if (mapRow.get("enabled") != null) {
            temp = mapRow.get("enabled").toString();
            mapRow.put("dispenabled", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
        }
        if (mapRow.get("realarea") != null) {
            temp = mapRow.get("realarea").toString();
            mapRow.put("disprealarea", datacodeCache.getValueDynamic("CboYesNo", temp, "code", "name"));
        }
        datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo","D1","code","name");
    }
    /**
     * @author: zhangjunyao
     * @date: 2022年3月4日
     * @param entity
     * @throws Exception
     * @return_type: void
     * @description: 提交审批后做的事情
     * @modify:
     */
    @Override
    protected void beforeSubmit(TapEntity entity, SessionUserBean sessionUserBean) {
        super.beforeSubmit(entity, sessionUserBean);
        // 添加审批流程id
        MmsProvinceCityMatchinfoEntity mmsProvinceCityMatchinfoEntity = (MmsProvinceCityMatchinfoEntity) entity;
        List<Map<String, Object>> flowidList = datacodeCache.getCodeListMap("ApprovalFlow_MmsProvinceCityMatchinfo",
                "code = 'MmsProvinceCityMatchinfo' ", "sortcode");
        if (!CollectionUtil.isEmpty(flowidList)) {
            mmsProvinceCityMatchinfoEntity.setFlowid(ConvertUtil.convertToLong(flowidList.get(0).get("id")));
        }
        List<String> fieldList = new ArrayList<>();
        fieldList.add(MmsProvinceCityMatchinfoEntity.FieldFlowid);
        this.updateFields(mmsProvinceCityMatchinfoEntity, fieldList);
    }
    /**
     * @param entity
     * @throws ServiceException
     * @description: 插入前操作，产生新的编码值，层次号
     * @author: hudeyong
     * @date: 2021-6-22 10:33:03
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) throws ServiceException {
        MmsProvinceCityMatchinfoEntity mmsProvinceCityMatchinfoEntity = (MmsProvinceCityMatchinfoEntity) entity;
        String userLevel = this.queryLevel(mmsProvinceCityMatchinfoEntity.getUsercode());
        // 如果当前人员为市级权限人员则需要添加审批流程
        if ("1".equals(userLevel)) {
            mmsProvinceCityMatchinfoEntity.setUseful("0");
        } else {
            mmsProvinceCityMatchinfoEntity.setUseful("1");
            mmsProvinceCityMatchinfoEntity.setState(9);
        }
        mmsProvinceCityMatchinfoEntity.setDocdate(new Date());
        mmsProvinceCityMatchinfoEntity.setDocno("");
        // 生成层次号
        String levelCode = mmsProvinceCityMatchinfoEntity.getArealevel();
        String parentId = ConvertUtil.convertToString(mmsProvinceCityMatchinfoEntity.getParentid());
        mmsProvinceCityMatchinfoEntity.setLevelcode(generateNewLevelCode(levelCode, parentId));
    }
    @Override
    protected void afterInsert(BasicEntity entity) throws ServiceException {
        super.afterInsert(entity);
        this.addValueToRedis(MmsProvinceCityMatchinfoEntity.tableName);
        MmsProvinceCityMatchinfoEntity  mmsPCentity = (MmsProvinceCityMatchinfoEntity) entity;
        if(MmsSystemConst.ProvinceCityUseful.isUseful(mmsPCentity.getUseful())){
          generateInstance(mmsPCentity);
        }
    }

    /**
      * @description:
      * @author xinfushuo
      * @param
      * @throws
      * @return
      * @date 2022/3/31
      * @modify
      */
    @Override
    public void generateInstance(MmsProvinceCityMatchinfoEntity entity){
        int  PmsDate = ConvertUtil.convertToInt(ParameterCache.getValue(MmsSystemConst.PmsProvinceCityUpdateDate));
        //约定日期之前 填本月 约定日期之后 填下一个月
        LocalDate now = LocalDate.now();
        if(now.getDayOfMonth()>PmsDate){
            now = now.plusMonths(1);
        }
        LocalDate end  = LocalDate.now().plusMonths(6).withDayOfMonth(1);
        LocalDate pmsEnableDate  = entity.getPmsenableddate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().withDayOfMonth(1);
        if(pmsEnableDate.withDayOfMonth(1).isBefore(now)||pmsEnableDate.withDayOfMonth(1).isEqual(now)){
            InsertProvinceInstance(now,end,entity);
        }else{
            InsertProvinceInstance(pmsEnableDate,end,entity);
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void InsertProvinceInstance(LocalDate start, LocalDate end, MmsProvinceCityMatchinfoEntity entity) {
        StringBufferProxy sql = new StringBufferProxy();
        List<Long> parentIds;
        List<BasicEntity> pmsEntities  = new ArrayList<>();
        String ParentLeveLCode  = entity.getLevelcode().substring(0,ConvertUtil.convertToInt(entity.getArealevel()) * 3 );
        LocalDate finalStart = start;
        Map<String,Object> paraMap = new HashMap<String,Object>();
        if(!ParentLeveLCode.contentEquals("")){
            paraMap.put("levelcode",ParentLeveLCode);
        }else{
            paraMap.put("deptcommoncode",entity.getDeptcommoncode());
        }
        paraMap.put("startmonth",YearMonth.of(finalStart.getYear(), finalStart.getMonthValue()));
        paraMap.put("endmonth",YearMonth.of(end.getYear(),end.getMonthValue()));
        List<Map<String,Object>> parents = pmsProvinceCityMatchInstanceService.queryMap(paraMap,"queryIdAndParentIdWithinMonth");
        if(!entity.getArealevel().contentEquals("0")){
            parentIds = parents.stream().map(map->ConvertUtil.convertToLong(map.get(PmsProvinceCityMatchInstanceEntity.FieldId))).collect(Collectors.toList());
        }else{
            parentIds = parents.stream().map(map->ConvertUtil.convertToLong(map.get("parentid"))).collect(Collectors.toList());
        }
        for (int i = 0; start.isBefore(end.withDayOfMonth(1)); i++) {
            long parentid  = parentIds.size()>0? parentIds.get(i): entity.getParentid();
            String ym = YearMonth.of(start.getYear(),start.getMonthValue()).format( DateTimeFormatter.ofPattern("yyyy-MM"));
            pmsEntities.add(pmsProvinceCityMatchInstanceService.assembleEntity(parentid,ym,entity)) ;
            start = start.plusMonths(1);
        }
        pmsProvinceCityMatchInstanceService.insertBatch(pmsEntities);
    }

    /**
     * @description: // 查询用户权限等级
     * @param: [userCode]
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/12 14:02
     * @modify:
     */
    @Override
    public String queryLevel(String userCode) throws ServiceException {
        StringBufferProxy sql = new StringBufferProxy();
        String userLevel = "";
        // 查询是否有市级权限
        sql.appendSingle(" arealevel = '1' and ','||areaauthorizationusercode||',' like '%,{0},%' ", userCode);
        MmsProvinceCityMatchinfoEntity mmsProvinceCityMatchinfoEntity = this.queryObjectByWhere(sql.toString());
        sql.clear();
        if (!ObjectUtils.isEmpty(mmsProvinceCityMatchinfoEntity)) {
            userLevel = "1";
        }
        // 查询是否有省级权限（当前用户为省级负责人情况）
        sql.appendSingle(" arealevel = '0' and ','||areaauthorizationusercode||',' like '%,{0},%' ", userCode);
        mmsProvinceCityMatchinfoEntity = this.queryObjectByWhere(sql.toString());
        sql.clear();
        if (!ObjectUtils.isEmpty(mmsProvinceCityMatchinfoEntity)) {
            userLevel = "0";
        }
        // 查询是否有省级权限（当前用户为省总或CFO情况）
        sql.appendSingle(" {0} = '{2}' or {1} = '{2}' ", MmsDeptExtraInfoEntity.FieldProvincemanagercode, MmsDeptExtraInfoEntity.FieldCfocode,
                userCode);
        MmsDeptExtraInfoEntity mmsDeptExtraInfoEntity = mmsDeptExtraInfoService.queryObjectByWhere(sql.toString());
        sql.clear();
        if (!ObjectUtils.isEmpty(mmsDeptExtraInfoEntity)) {
            userLevel = "0";
        }
        return userLevel;
    }

    /**
     * @description: // 构造树
     * @param: [userCode]
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/20 19:22
     * @modify:
     */
    @Override
    public List<TreeModel> queryTreeList(String userCode) {
        List<Map<String, Object>> listModule = new ArrayList<>();
        StringBufferProxy sql = new StringBufferProxy();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("usercode", userCode);
        // 数据权限
        String dataPermission = this.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "",MmsProvinceCityMatchinfoEntity.tableName, getSessionUserBean());
        if (!StringUtil.isEmpty(dataPermission)) {
            paramMap.put("qry_where", dataPermission);
            listModule = this.queryMap(paramMap, "queryDataPermission");
            listModule = listModule.stream().distinct().collect(Collectors.toList());
        } else {
            //如果是运营人员，返回所有一级部门
            if (checkIsOperators()) {
                listModule = this.queryMap(paramMap, "queryAll");
            } else if (checkIsTop()) { // 如果是省总或财总或CHO，返回省总或财总或CHO是当前用户的部门
                sql.appendSingle(" PROVINCEMANAGERCODE = '{0}' or PROVINCECHOCODE = '{0}' or CFOCODE = '{0}' ", userCode);
                List<MmsDeptExtraInfoEntity> mmsDeptExtraInfoEntities = mmsDeptExtraInfoService.queryByWhere(sql.toString());
                sql.clear();
                List<String> deptcommoncodesList = mmsDeptExtraInfoEntities.stream().map(MmsDeptExtraInfoEntity::getDeptcommoncode).collect(Collectors.toList());
                String deptcommoncodes = "'" + String.join("','", deptcommoncodesList) + "'";
                paramMap.put("deptcommoncodes", deptcommoncodes);
                listModule = this.queryMap(paramMap, "queryTops");
            } else if (checkIsProvinces()) { // 如果省级
                listModule = this.queryMap(paramMap, "queryProvinces");
            } else if (checkIsCitys()) { // 如果是市级经营单位则返回市级及其下属经营单位
                listModule = this.queryMap(paramMap, "queryCitys");
            } else if (checkIsMatchs()) { //县级
                listModule = this.queryMap(paramMap, "queryMatchs");
            }
        }
        List<Map<String, Object>> listNewModule = new ArrayList<Map<String, Object>>();
        listNewModule.addAll(listModule);
        TreeModel treeModel = new TreeModel();
        List<TreeModel> treeList = treeModel.buildTree(listNewModule, true, "全国");
        return treeList;
    }

    /**
     * @param
     * @return
     * @description: 判断是否为运营人员
     * @author: hudeyong
     * @date: 2021-06-24
     * @modify:
     */
    @Override
    public Boolean checkIsOperators() {
        boolean key = false;
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("code", MmsSystemConst.ItemsEnum.bspOperators);
        paraMap.put("usercode", getSessionUserBean().getUser().getCode());
        int count = this.getCount(paraMap, "getOperatorsCount");
        if (count > 0) {
            return true;
        }
        return key;
    }

    /**
     * @description: // 检查当前用户是否省总或财总或CHO
     * @param: []
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/10 16:30
     * @modify:
     */
    @Override
    public Boolean checkIsTop() {
        boolean key = false;
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("usercode", getSessionUserBean().getUser().getCode());
        int count = this.getCount(paraMap, "getTopCount");
        if (count > 0) {
            return true;
        }
        return key;
    }

    /**
     * @description: // 检查当前用户是否省总或财总或CHO
     * @param: []
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/10 16:30
     * @modify:
     */
    @Override
    public Boolean checkIsProvinces() {
        boolean key = false;
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("usercode", getSessionUserBean().getUser().getCode());
        int count = this.getCount(paraMap, "getProvincesCount");
        if (count > 0) {
            return true;
        }
        return key;
    }

    /**
     * @description: // 检查当前用户是否市级负责人
     * @param: []
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/10 16:30
     * @modify:
     */
    @Override
    public Boolean checkIsCitys() {
        boolean key = false;
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("usercode", getSessionUserBean().getUser().getCode());
        int count = this.getCount(paraMap, "getCitysCount");
        if (count > 0) {
            return true;
        }
        return key;
    }

    /**
     * @description: // 检查当前人员是否县级人员
     * @param: []
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/21 15:29
     * @modify:
     */
    @Override
    public Boolean checkIsMatchs() {
        boolean key = false;
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("usercode", getSessionUserBean().getUser().getCode());
        int count = this.getCount(paraMap, "getMatchsCount");
        if (count > 0) {
            return true;
        }
        return key;
    }

    /**
     * @description: // 市级申请审批结束数据回写
     * @param: []
     * @return:
     * @author: wanghjielei
     * @date: 2022/1/12 16:58
     * @modify:
     */
    public void rewriteMmsProvinceCityMatchinfo(Long sourceId) {
        MmsProvinceCityMatchinfoEntity mmsProvinceCityMatchinfoEntity = this.queryById(sourceId.toString());
        if (!MmsSystemConst.ProvinceCityUseful.isUseful(mmsProvinceCityMatchinfoEntity.getUseful())) {
            mmsProvinceCityMatchinfoEntity.setUseful(MmsSystemConst.ProvinceCityUseful.CURRENT_ENABLED);
            mmsProvinceCityMatchinfoEntity.setUsefuldate(new Date());
            this.generateInstance(mmsProvinceCityMatchinfoEntity);
        } else {
            mmsProvinceCityMatchinfoEntity.setUseful(MmsSystemConst.ProvinceCityUseful.CURRENT_DISABLED);
            mmsProvinceCityMatchinfoEntity.setUsefuldate(null);
            pmsProvinceCityMatchInstanceService.syncDisabled(mmsProvinceCityMatchinfoEntity);
        }
        List<String> fieldList = new ArrayList<>();
        fieldList.add(MmsProvinceCityMatchinfoEntity.FieldUseful);
        this.updateFields(mmsProvinceCityMatchinfoEntity, fieldList);
    }

    /**
     * @param map
     * @throws ServiceException
     * @description: 更新前，同时更新下级
     * @author: hudeyong
     * @date: 2021-6-22 10:33:03
     * @modify:
     */
    @Override
    protected void updateBefore(Map<String, Object> map) throws ServiceException {
        StringBufferProxy sql = new StringBufferProxy();
        String id = ConvertUtil.convertToString(map.get(MmsProvinceCityMatchinfoEntity.FieldId));
        MmsProvinceCityMatchinfoEntity oldEntity = this.queryById(id);
        String oldlevelCode = ConvertUtil.convertToString(map.get(MmsProvinceCityMatchinfoEntity.FieldLevelcode));
        //更新下级区域层次号
        if (!oldlevelCode.isEmpty() && isParentIdChange(map, oldEntity)) {
            String areaLevel = ConvertUtil.convertToString(map.get(MmsProvinceCityMatchinfoEntity.FieldArealevel));
            String newParentId = ConvertUtil.convertToString(map.get(MmsProvinceCityMatchinfoEntity.FieldParentid));
            String newLevelCode = generateNewLevelCode(areaLevel, newParentId);
            map.put(MmsProvinceCityMatchinfoEntity.FieldLevelcode, newLevelCode);
            sql.appendSingle(
                    "update {0} set levelcode = replace(levelcode, substr(levelcode ,0,'{1}'), '{2}') where levelcode like '{3}%' and levelcode != '{3}'",
                    MmsProvinceCityMatchinfoEntity.tableName, oldlevelCode.length(), newLevelCode, oldlevelCode);
            this.updateExecute(sql.toString());
        }
        sql.clear();
        //更新下级一级部门
        if (!oldlevelCode.isEmpty()&&isDeptCommonCodeChange(map, oldEntity)) {
            if (!oldEntity.getArealevel().equals(AreaLevelEnum.PROVINCE)) {
                throw new ServiceException("只能修改省级区域的一级部门，修改后，该区域下的地区自动修改！");
            }
            String deptCommonCode = ConvertUtil.convertToString(map.get(MmsProvinceCityMatchinfoEntity.FieldDeptcommoncode));
            sql.appendSingle(
                    "update {0} set deptcommoncode = '{1}' where levelcode like '{2}%'  and levelcode != '{2}'",
                    MmsProvinceCityMatchinfoEntity.tableName, deptCommonCode, oldlevelCode);
            this.updateExecute(sql.toString());
        }
    }

    /**
     * @param map
     * @return
     * @description: 判断一级部门是否改变
     * @author: hudeyong
     * @date: 2021-06-23 10:50:41
     * @modify:
     */
    private boolean isDeptCommonCodeChange(Map<String, Object> map, MmsProvinceCityMatchinfoEntity oldEntity) {
        String newDeptCommonCode = ConvertUtil.convertToString(map.get(MmsProvinceCityMatchinfoEntity.FieldDeptcommoncode));
        String oldDeptCommonCode = ConvertUtil.convertToString(oldEntity.getDeptcommoncode());
        return !Objects.equals(newDeptCommonCode, oldDeptCommonCode);
    }

    /**
     * @param map
     * @return
     * @description: 判断上级区域是否改变
     * @author: hudeyong
     * @date: 2021-06-23 10:50:41
     * @modify:
     */
    private boolean isParentIdChange(Map<String, Object> map, MmsProvinceCityMatchinfoEntity oldEntity) {
        String newParentId = ConvertUtil.convertToString(map.get(MmsProvinceCityMatchinfoEntity.FieldParentid));
        String oldParentId = ConvertUtil.convertToString(oldEntity.getParentid());
        return !Objects.equals(newParentId, oldParentId);
    }

    /**
     * @param areaLevel,parentId
     * @throws ServiceException
     * @description: 生成层次号
     * @author: hudeyong
     * @date: 2021-6-22 14:27:03
     * @modify:
     */
    public String generateNewLevelCode(String areaLevel, String parentId) {
        String newAreaLevel = "";
        StringBufferProxy sql = new StringBufferProxy();
        //同上级的同级区域层级号
        String sameLevelCode = "";
        //用于计算层次号长度 省级 1 市级 2 县级 3
        int index = 1;
        //如果是省级区域
        if (areaLevel.equals(AreaLevelEnum.PROVINCE)) {
            //查找同等级区域，按创建时间降序排序
            sql.appendSingle(" areaLevel = '{0}' ORDER BY LEVELCODE DESC ", areaLevel);
            List<MmsProvinceCityMatchinfoEntity> mmsProvinceCityMatchinfoEnties = mmsProvinceCityMatchinfoService.queryByWhere(sql.toString());
            //没有数据，赋初始值001
            if (mmsProvinceCityMatchinfoEnties.size() == 0) {
                return firstLevelCode;
            }
            sameLevelCode = mmsProvinceCityMatchinfoEnties.get(0).getLevelcode();
        } else { //如果是市级或县级区域
            //查找上级区域
            MmsProvinceCityMatchinfoEntity mmsProvinceCityMatchinfoEntity = mmsProvinceCityMatchinfoService.queryById(parentId);
            if (mmsProvinceCityMatchinfoEntity == null) {
                throw new ServiceException("请先添加上级区域！");
            }
            if (mmsProvinceCityMatchinfoEntity.getArealevel().equals(areaLevel)) {
                throw new ServiceException("区域级别选择错误！");
            }
            //上级区域层级号
            String higherLevelCode = mmsProvinceCityMatchinfoEntity.getLevelcode();
            if (areaLevel.equals(AreaLevelEnum.CITY)) {
                //如果区域级别为市级，上级区域为县级
                if (mmsProvinceCityMatchinfoEntity.getArealevel().equals(AreaLevelEnum.COUNTY)) {
                    throw new ServiceException("区域级别选择错误！");
                }
                index = 2;
            } else {
                index = 3;
            }
            sql.clear();
            //查找同上级区域，按层次号降序排序
            sql.appendSingle(" areaLevel = '{0}'and parentid = '{1}' ORDER BY LEVELCODE DESC ", areaLevel, parentId);
            List<MmsProvinceCityMatchinfoEntity> mmsProvinceCityMatchinfoEnties = mmsProvinceCityMatchinfoService.queryByWhere(sql.toString());
            if (mmsProvinceCityMatchinfoEnties.size() == 0) {
                return higherLevelCode + firstLevelCode;
            }
            sameLevelCode = mmsProvinceCityMatchinfoEnties.get(0).getLevelcode();
        }
        //最新同上级区域的层次号+1
        String preAreaLevel = String.valueOf(Integer.parseInt(sameLevelCode) + 1);
        //长度大于3 * index位时，提示失败
        if (preAreaLevel.length() > levelCodelen * index) {
            throw new ServiceException("层次号赋值失败，请联系管理员！");
        }
        //code前面补0凑3 * index位
        newAreaLevel = codes[levelCodelen * index - preAreaLevel.length()] + preAreaLevel;

        return newAreaLevel;
    }


//	/**
//	 * @description: 生成编码
//	 * @param entity
//	 * @throws ServiceException
//	 * @author: hudeyong
//	 * @date: 2021-6-22 14:27:03
//	 * @modify:
//	 */
//	public String generateNewCode() {
//		String newCode = "";
//		//查找最新一条数据，如果没有数据，编号则为000001，否则递增
//		List<MmsProvinceCityMatchinfoEntity> mmsProvinceCityMatchinfoEnties = mmsProvinceCityMatchinfoService.queryByWhere("1=1 ORDER BY CODE DESC");
//		if(mmsProvinceCityMatchinfoEnties.size()==0) {
//			newCode = firstCode;
//		}else {
//			//最新编码+1
//			String preCode = String.valueOf(Integer.parseInt(mmsProvinceCityMatchinfoEnties.get(0).getCode()) + 1);
//			//长度大于6位时，提示失败
//			if(preCode.length()>codeLen) {
//				throw new ServiceException("编号赋值失败，请联系管理员！");
//			}
//			//code前面补0凑6位
//			newCode = codes[codeLen-preCode.length()]+preCode;
//		}
//		return newCode;
//	}

    /**
     * @param parentid
     * @throws ServiceException
     * @description: 根据parentid找到所有上级区域
     * @author: hudeyong
     * @date: 2021-7-08
     * @modify:
     */
    public List<MmsProvinceCityMatchinfoEntity> acquireAreaByParentId(long parentid) {
        List<MmsProvinceCityMatchinfoEntity> areas = new ArrayList<>();
        MmsProvinceCityMatchinfoEntity mmsProvinceCityMatchinfoEntity;
        while (parentid != 0) {
            mmsProvinceCityMatchinfoEntity = mmsProvinceCityMatchinfoService.queryById(ConvertUtil.convertToString(parentid));
            if (mmsProvinceCityMatchinfoEntity == null) {
                break;
            }
            parentid = mmsProvinceCityMatchinfoEntity.getParentid();
            areas.add(mmsProvinceCityMatchinfoEntity);
        }
        return areas;
    }

    /**
     * @param paraMap
     * @throws ServiceException
     * @description: 根据工号找到这个人的所有上级区域（可添加筛选条件：创建部门编号）
     * @author: hudeyong
     * @date: 2021-7-08
     * @modify:
     */
    @Override
    public List<MmsProvinceCityMatchinfoEntity> acquireAllUpArea(Map<String, Object> paraMap) {
        List<MmsProvinceCityMatchinfoEntity> resultMap = new ArrayList<>();
        String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" ','||AREAAUTHORIZATIONUSERCODE||',' like '%,{0},%' ", userCode);
        if (paraMap.containsKey("deptcommomcode")) {
            sql.appendSingle(" and deptcommomcode = '{0}'", ConvertUtil.convertToString(paraMap.get("deptcommomcode")));
        }
        List<MmsProvinceCityMatchinfoEntity> oldMmsProvinceCityMatchinfoEntities = mmsProvinceCityMatchinfoService.queryByWhere(sql.toString());
        //省市信息获取上级
        for (MmsProvinceCityMatchinfoEntity provinceCityMatchinfoEntity : oldMmsProvinceCityMatchinfoEntities) {
            resultMap.addAll(acquireAreaByParentId(provinceCityMatchinfoEntity.getId()));
            resultMap.addAll(acquireAreaByParentId(provinceCityMatchinfoEntity.getParentid()));
        }
        sql.clear();
        sql.appendSingle("{0} like '%,{1},%' ",SQLAdapter.concat(new String[]{"','",MmsDeptProvinceCityMatchInfoEntity.FieldUsercodes,"','"}), userCode);
        if (paraMap.containsKey("deptcommomcode")) {
            sql.appendSingle(" and deptcommomcode = '{0}'", ConvertUtil.convertToString(paraMap.get("deptcommomcode")));
        }
        List<MmsDeptProvinceCityMatchInfoEntity> mmsDeptProvinceCityMatchInfoEntities =mmsDeptProvinceCityMatchInfoService.queryByWhere(sql.toString());
        //添加特殊部门获取上级
        for (MmsDeptProvinceCityMatchInfoEntity deptProvinceCityMatchInfoEntity : mmsDeptProvinceCityMatchInfoEntities) {
            resultMap.addAll(acquireAreaByParentId(deptProvinceCityMatchInfoEntity.getParentid()));
        }
        return resultMap;
    }

    /**
     * @param paraMap
     * @throws ServiceException
     * @description: 根据工号返回用户所有有权限的区域（可添加筛选条件：创建部门编号）级联类型
     * @author: hudeyong
     * @date: 2021-11-30
     * @modify:
     */
    @Override
    public List<Map<String, Object>> acquireCascaderAllLowerArea(Map<String, Object> paraMap) {
        List<Map<String, Object>> list = acquireAllLowerArea(paraMap);
        List<Map<String, Object>> resultMap = new ArrayList<Map<String, Object>>();
        //省
        List<Map<String, Object>> list0 = new ArrayList<Map<String, Object>>();
        //市
        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
        //县
        List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
//		Map<String, Object> map = new HashMap<String, Object>();
        // 分装省市县
        for (Map<String, Object> areaMap : list) {
            areaMap.put("value", areaMap.get("levelcode"));
            areaMap.put("text", areaMap.get("name"));
            areaMap.put("label", areaMap.get("name"));
            areaMap.put("disabled", false);
            if ("0".equals(areaMap.get("arealevel"))) {
                list0.add(areaMap);
            } else if ("1".equals(areaMap.get("arealevel"))) {
                list1.add(areaMap);
            } else {
                list2.add(areaMap);
            }
        }
        list1 = aplitAreaList(list2, list1);
        resultMap = aplitAreaList(list1, list0);
        return resultMap;
    }

    /**
     * @author: chengengwei
     * @date: 2021-12-06
     * @description: 获取省市县名称
     * @modify:
     */
    @Override
    public String getDispdeptname(String deptname1, String deptname2, String deptname3) {
        DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
        String temp = "";
        if (!StringUtil.isEmpty(deptname3)) {
            temp = datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", deptname1, "code", "name") + "/"
                    + datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", deptname2, "code", "name") + "/"
                    + datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", deptname3, "code", "name");
        } else if (!StringUtil.isEmpty(deptname2)) {
            temp = datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", deptname1, "code", "name") + "/"
                    + datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", deptname2, "code", "name");
        } else {
            temp = datacodeCache.getValueDynamic("MmsProvinceCityMatchinfo", deptname1, "code", "name");
        }
        return temp;
    }

    public List<Map<String, Object>> aplitAreaList(List<Map<String, Object>> lowList, List<Map<String, Object>> topList) {
        List<Map<String, Object>> newlist = new ArrayList<Map<String, Object>>();
        StringBufferProxy sql = new StringBufferProxy();
        //处理县，找上级，存到上级
        top:
        for (Map<String, Object> lowMap : lowList) {
            for (Map<String, Object> topMap : topList) {
                // 如果此县属于市
                if (topMap.get("id").equals(lowMap.get("parentid"))) {
                    lowMap.put("parentcode", topMap.get("levelcode"));
                    // 如果已经创建了list
                    if (topMap.containsKey("children")) {
                        newlist = (List<Map<String, Object>>) topMap.get("children");
                        newlist.add(lowMap);
                        continue top;
                    } else {
                        newlist = new ArrayList<>();
                        newlist.add(lowMap);
                        topMap.put("children", newlist);
                        continue top;
                    }
                }
            }
            sql.clear();
            sql.appendSingle("select * from MMSPROVINCECITYMATCHINFO where  id = '{0}'", lowMap.get("parentid"));
            //遍历后如果找不到县的上级，需要通过sql查询。
            List<Map<String, Object>> newMaplist = this.selectExecute(sql.toString());
            if (newMaplist.size() == 0) {
                continue;
            }
            Map<String, Object> newMap = newMaplist.get(0);
            newMap.put("value", ConvertUtil.convertToString(newMap.get("levelcode")));
            newMap.put("text", ConvertUtil.convertToString(newMap.get("name")));
            newMap.put("label", ConvertUtil.convertToString(newMap.get("name")));
            newMap.put("disabled", true);
            lowMap.put("parentcode", newMap.get("levelcode"));
            newlist = new ArrayList<>();
            newlist.add(lowMap);
            newMap.put("children", newlist);
            topList.add(newMap);
        }
        return topList;
    }

    /**
     * @param paraMap
     * @throws ServiceException
     * @description: 根据工号返回用户所有有权限的区域（可添加筛选条件：创建部门编号）
     * @author: hudeyong
     * @date: 2021-6-24 16:36:21
     * @modify:
     */
    @Override
    public List<Map<String, Object>> acquireAllLowerArea(Map<String, Object> paraMap) {
        List<Map<String, Object>> resultMap = new ArrayList<Map<String, Object>>();
        StringBufferProxy sql = new StringBufferProxy();
        String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
        //获取用户作为CEFHO的部门
        sql.appendSingle("PROVINCEMANAGERCODE = '{0}' or PROVINCECHOCODE = '{0}' or CFOCODE = '{0}'", userCode);
        List<MmsDeptExtraInfoEntity> mmsDeptExtraInfoEntities = mmsDeptExtraInfoService.queryByWhere(sql.toString());
        sql.clear();
        //查询用户拥有授权 或 用户作为CEFHO的区域 或 参数中deptcommon包含的 区域
        List<MmsProvinceCityMatchinfoEntity> oldMmsProvinceCityMatchinfoEntities = acquireAllLowerProvinceMatch(paraMap, mmsDeptExtraInfoEntities);
        List<MmsDeptProvinceCityMatchInfoEntity> oldMmsDeptProvinceCityMatchInfoEntities = acquireAllLowerDeptProvinceMatch(paraMap,mmsDeptExtraInfoEntities);
        List<String> strCodeList = trimMatchInfos(oldMmsProvinceCityMatchinfoEntities,oldMmsDeptProvinceCityMatchInfoEntities);
        if (strCodeList.size()>0) {
        	for (String levelcode : strCodeList) {
                sql.appendSingle(" levelCode like '{0}%' or", levelcode);
            }
        	List<Map<String, Object>> mmsProvinceCitys = mmsProvinceCityMatchinfoService.queryMapByWhere(sql.toString().substring(0, sql.toString().length() - 2) + " ORDER BY DEPTCOMMONCODE,LEVELCODE");
            resultMap.addAll(mmsProvinceCitys);
        }
        List<Map<String, Object>> list = resultMap.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(m -> m.get("levelcode").toString()))
                        ), ArrayList::new
                ));
        return list;
    }

    protected List<String> trimMatchInfos(List<MmsProvinceCityMatchinfoEntity> matchInfos1, List<MmsDeptProvinceCityMatchInfoEntity> matchInfos2){
		Stack<String> areaStack = new Stack<>();

		for (int i = 0; i < matchInfos1.size(); i++) {
			String levelcode = ConvertUtil.convertToString(matchInfos1.get(i).getLevelcode());
			if(!areaStack.isEmpty()){
				int lengthOfTop = areaStack.peek().length();
				if(levelcode.length() > lengthOfTop && levelcode.substring(0,lengthOfTop).contentEquals(areaStack.peek())){
					continue;
				}else{
					areaStack.push(levelcode);
				}
			}else{
				areaStack.push(levelcode);
			}
		}
		for (int i = 0; i < matchInfos2.size(); i++) {
			String levelcode = ConvertUtil.convertToString(matchInfos2.get(i).getArealevelcode());
			if(!areaStack.isEmpty()){
				int lengthOfTop = areaStack.peek().length();
				if(levelcode.length() > lengthOfTop && levelcode.substring(0,lengthOfTop).contentEquals(areaStack.peek())){
					continue;
				}else{
					areaStack.push(levelcode);
				}
			}else{
				areaStack.push(levelcode);
			}
		}
		return areaStack.stream().collect(Collectors.toList());
	}

    /**
     * @param paraMap deptcommoncode
     * @param  paraMap usercode
     * @return
     * @throws
     * @description: 查询用户拥有授权 或 用户作为CEFHO的区域 或 参数中deptcommon包含的 区域取
     * @author xinfushuo
     * @date 2022/2/25
     * @modify
     */
    private List<MmsProvinceCityMatchinfoEntity> acquireAllLowerProvinceMatch(Map paraMap, List<MmsDeptExtraInfoEntity> mmsDeptExtraInfoEntities) {
        StringBufferProxy sql = new StringBufferProxy();
        String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
        //获取用户有权限的区域
        sql.appendSingle(" ','||AREAAUTHORIZATIONUSERCODE||',' like '%,{0},%' ", userCode);
        StringBuilder sb = new StringBuilder();
        //参数包含deptcommoncode
        if (paraMap.containsKey("deptcommomcode")) {
            sb.append("'" + ConvertUtil.convertToString(paraMap.get("deptcommomcode")) + "'");
        }
        //若用户为部门CEFHO
        if (mmsDeptExtraInfoEntities.size() > 0) {
            if (paraMap.containsKey("deptcommomcode")) {
                sb.append(",");
            }
            for (int i = 0; i < mmsDeptExtraInfoEntities.size(); i++) {
                sb.append("'" + mmsDeptExtraInfoEntities.get(i).getDeptcommoncode() + "'");
                if (i < mmsDeptExtraInfoEntities.size() - 1) {
                    sb.append(",");
                }
            }
        }
        if (sb.toString().length() > 0) {
            sql.appendSingle(" or DEPTCOMMONCODE in ({0}) ", sb.toString());
        }
        sql.appendSingle(" ORDER BY DEPTCOMMONCODE,LEVELCODE");
        //查询用户拥有授权 或 用户作为CEFHO的区域 或 参数中deptcommon包含的 区域
        List<MmsProvinceCityMatchinfoEntity> oldMmsProvinceCityMatchinfoEntities = mmsProvinceCityMatchinfoService.queryByWhere(sql.toString());
        return oldMmsProvinceCityMatchinfoEntities;
    }

    /**
     * @param
     * @return
     * @throws
     * @description: 查询用户拥有授权 或 用户作为CEFHO的区域 或 参数中deptcommon包含的 区域
     * @author xinfushuo
     * @date 2022/2/25
     * @modify
     */
    private List<MmsDeptProvinceCityMatchInfoEntity> acquireAllLowerDeptProvinceMatch(Map paraMap, List<MmsDeptExtraInfoEntity> mmsDeptExtraInfoEntities) {
        StringBufferProxy sql = new StringBufferProxy();
        String userCode = ConvertUtil.convertToString(paraMap.get("usercode"));
        //获取用户有权限的区域
        sql.appendSingle("{0} like '%,{1},%' ",SQLAdapter.concat(new String[]{"','",MmsDeptProvinceCityMatchInfoEntity.FieldUsercodes,"','"}), userCode);
        List<String> specialdeptcommoncode = new ArrayList<>();
        //获取用户所在特殊部门配置省区编码
        List<Map<String, Object>> rangelist = datacodeCache.getCodeListMap(MmsSystemConst.DeptcommonProvinceViewRange, "", "sortcode");
        Map<String, String> rangeMap = rangelist.stream().collect(Collectors.toMap(map -> ConvertUtil.convertToString(map.get("code")), map -> ConvertUtil.convertToString(map.get("name"))));
        if (mmsDeptExtraInfoEntities.size() > 0) {
            specialdeptcommoncode.addAll(
                    mmsDeptExtraInfoEntities.stream().filter(dept -> {
                        return rangeMap.containsKey(dept.getDeptcommoncode());
                    }).map(dept -> dept.getDeptcommoncode()).collect(Collectors.toList())
            );
        }
        //若用户为特殊省区CEFHO则将编码中对应的范围
        if (specialdeptcommoncode.size() > 0) {
            List<String> authDeptcommoncodelist = new ArrayList<>();
            for (int i = 0; i < specialdeptcommoncode.size(); i++) {
                authDeptcommoncodelist.addAll(new ArrayList<>(Arrays.asList(mmsDeptProvinceCityMatchInfoService.getRangeFromDeptCommoncode(specialdeptcommoncode.get(0)).split(","))));
            }
            Set<String> sqlSet = new HashSet<>(authDeptcommoncodelist);
            String alldeptcommoncode = sqlSet.stream().map(s -> "'".concat(s).concat("'")).collect(Collectors.joining(","));
            sql.appendSingle(" or DEPTCOMMONCODE in ({0}) ", alldeptcommoncode);
        }
        //根据参数中的deptommoncode获取权限
        String paramDeptcommoncode = "";
        if(paraMap.containsKey("deptcommomcode")){
            paramDeptcommoncode  = ConvertUtil.convertToString(paraMap.get("deptcommomcode"));
        }
        if(!paramDeptcommoncode.isEmpty()){
            sql.appendSingle(" or DEPTCOMMONCODE  = '{0}' ", paramDeptcommoncode);
        }
        List<MmsDeptProvinceCityMatchInfoEntity> mmsDeptProvinceCityMatchInfoEntities  =   mmsDeptProvinceCityMatchInfoService.queryByWhere(sql.toString());
        return mmsDeptProvinceCityMatchInfoEntities;
    }


    public boolean checkPower(String usercode) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" ','||AREAAUTHORIZATIONUSERCODE||',' like '%,{0},%' ", usercode);
        List<MmsProvinceCityMatchinfoEntity> oldMmsProvinceCityMatchinfoEntities = mmsProvinceCityMatchinfoService.queryByWhere(sql.toString());
        if (oldMmsProvinceCityMatchinfoEntities.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    protected void updateAfter(Map<String, Object> map) throws ServiceException {
        super.updateAfter(map);
        pmsProvinceCityMatchInstanceService.syncAuthUser(ConvertUtil.convertToString(map.get(PmsProvinceCityMatchInstanceEntity.FieldLevelcode))
                                            ,ConvertUtil.convertToString(map.get(PmsProvinceCityMatchInstanceEntity.FieldAreaauthorizationusercode))
                                            ,ConvertUtil.convertToString(map.get(PmsProvinceCityMatchInstanceEntity.FieldAreaauthorizationusername)));
        this.addValueToRedis(MmsProvinceCityMatchinfoEntity.tableName);
    }



    @Override
    protected void deleteAfter(String whereSql) {
        super.deleteAfter(whereSql);
        this.addValueToRedis(MmsProvinceCityMatchinfoEntity.tableName);
    }

    /**
     * @param list
     * @throws ServiceException
     * @description: 重写导入的数据额外处理函数，添加需要导入的数据
     * @author: zhangjunyao
     * @date: 2022-01-24
     * @modify:
     */
    @Override
    public void expandProcessExcelData(List<Map<String, String>> list) {
        super.expandProcessExcelData(list);
        String deptCommonCodeId = "10" + list.get(0).get("deptcommoncode");
        Map<String, String> provinceIdMap = new HashMap<>();
        List<String> provinceAuthorizedUserList = new ArrayList<String>();
        String provinceLevelCode = generateNewLevelCode(AreaLevelEnum.PROVINCE, deptCommonCodeId);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String parseDate = simpleDateFormat.format(date);
        // 生成基本字段数据，生成省级数据的parentid
        for (Map<String, String> mapRow : list) {
            // 每条数据赋值id
            long[] arrayId = PrimaryKeyUtil.GeneIDs(MmsProvinceCityMatchinfoEntity.tableName, 1);
            mapRow.put("id", ConvertUtil.convertToString(arrayId[0]));
            // 系统自带字段赋值
            mapRow.put("state", "9");
            mapRow.put("useful", "1");
            mapRow.put("createon", parseDate);
            mapRow.put("modifiedon", parseDate);
            mapRow.put("docdate", parseDate);
            mapRow.put("usercode", this.getSessionUserBean().getUser().getCode());
            mapRow.put("username", this.getSessionUserBean().getUser().getName());
            mapRow.put("deptcode", this.getSessionUserBean().getDept().getCode());
            mapRow.put("deptname", this.getSessionUserBean().getDept().getFullname());
            // 编号、区域名称编号赋值
            String name = mapRow.get("name");
            String areaLevel = mapRow.get("arealevel");
            String code = datacodeCache.getValueDynamic("DeptCommonCode2", name, "name", "code");
            mapRow.put("code", code);
            mapRow.put("namecode", code);
            // 生成省级数据的parentid、层次号，并记录其id为市级数据赋值parentid
            if (areaLevel.equals(AreaLevelEnum.PROVINCE)) {
                mapRow.put("parentid", deptCommonCodeId);
                provinceIdMap.put(name, ConvertUtil.convertToString(arrayId[0]));
                mapRow.put("levelcode", provinceLevelCode);
                provinceAuthorizedUserList.add(mapRow.get(MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode));
                provinceLevelCode = String.valueOf(Integer.parseInt(provinceLevelCode) + 1);
                provinceLevelCode = codes[levelCodelen - provinceLevelCode.length()] + provinceLevelCode;
            }
        }
        provinceLevelCode = String.valueOf(Integer.parseInt(provinceLevelCode) - 1);
        provinceLevelCode = codes[levelCodelen - provinceLevelCode.length()] + provinceLevelCode;
        String cityLevelCode = provinceLevelCode + firstLevelCode;
        Map<String, String> cityIdMap = new HashMap<>();
        // 生成市级数据的parentid、层次号
        for (Map<String, String> mapRow : list) {
            String areaLevel = mapRow.get("arealevel");
            if (areaLevel.equals(AreaLevelEnum.CITY)) {
                String parentName = mapRow.get("parentname");
                if (provinceIdMap.containsKey(parentName)) {
                    mapRow.put("parentid", provinceIdMap.get(parentName));
                    cityIdMap.put(mapRow.get("name"), mapRow.get("id"));
                }
                // 如果是市直属单位则其上级区域为市级
                if (mapRow.get("areatype").equals("1")) {
                    if (cityIdMap.containsKey(parentName)) {
                        mapRow.put("parentid", cityIdMap.get(parentName));
                    }
                }
                mapRow.put("levelcode", cityLevelCode);
                cityLevelCode = String.valueOf(Integer.parseInt(cityLevelCode) + 1);
                cityLevelCode = codes[levelCodelen * 2 - cityLevelCode.length()] + cityLevelCode;
            }
        }
        cityLevelCode = String.valueOf(Integer.parseInt(cityLevelCode) - 1);
        cityLevelCode = codes[levelCodelen * 2 - cityLevelCode.length()] + cityLevelCode;
        String countryLevelCode = cityLevelCode + firstLevelCode;
        // 生成县级数据的parentid、层次号
        for (Map<String, String> mapRow : list) {
            String areaLevel = mapRow.get("arealevel");
            if (areaLevel.equals(AreaLevelEnum.COUNTY)) {
                String parentName = mapRow.get("parentname");
                if (cityIdMap.containsKey(parentName)) {
                    mapRow.put("parentid", cityIdMap.get(parentName));
                }
                mapRow.put("levelcode", countryLevelCode);
                countryLevelCode = String.valueOf(Integer.parseInt(countryLevelCode) + 1);
                countryLevelCode = codes[levelCodelen * 3 - countryLevelCode.length()] + countryLevelCode;
            }
        }
    }

    /**
     * @param ids
     * @description: 实现级联删除
     * @author: zhangjunyao
     * @date: 2022-02-15
     * @modify:
     */
    @Override
    public void deleteCascade(String ids) {
        StringBufferProxy sql = new StringBufferProxy();
        List<MmsProvinceCityMatchinfoEntity> mmsProvinceCityMatchinfoEntities = this.queryByIds(ids);
        int areaLevel = ConvertUtil.convertToInt(mmsProvinceCityMatchinfoEntities.get(0).getArealevel());
        this.deleteByIds(ids);
        if (areaLevel == 2) {
            return;
        }
        while (areaLevel < 2) {
            areaLevel++;
            sql.appendSingle(" parentid in ({0}) ", ids);
            mmsProvinceCityMatchinfoEntities = this.queryByWhere(sql.toString());
            this.deleteByWhere(sql.toString());
            if (CollectionUtil.isEmpty(mmsProvinceCityMatchinfoEntities)) {
                break;
            }
            ids = mmsProvinceCityMatchinfoEntities.stream().map(entity -> ConvertUtil.convertToString(entity.getId()))
                    .collect(Collectors.joining("','", "'", "'"));
            sql.clear();
        }
    }

    /**
     * @param
     * @description: 查询市级区域
     * @author: zhangjunyao
     * @date: 2022-02-26
     * @modify:
     */
    @Override
    public List<String> queryCity() {
        String userCode = getSessionUserBean().getUser().getCode();
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" ','||{0}||',' like '%{1}%' and {2} = {3} ", MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                userCode, MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.CITY);
        List<MmsProvinceCityMatchinfoEntity> mmsProvinceCityMatchinfoEntity = this.queryByWhere(sql.toString());
        List<String> cityNameList = mmsProvinceCityMatchinfoEntity.stream().map(entity -> entity.getName()).collect(Collectors.toList());
        return cityNameList;
    }

    /**
     * @param
     * @description: 根据用户权限拼接sql查询区域（用于点击左树加载右列表list方法）
     * @author: zhangjunyao
     * @date: 2022-03-01
     * @modify:
     */
    @Override
    public void spellSqlByUserLevel(StringBufferProxy sql, String id) {
        String userCode = this.getSessionUserBean().getUser().getCode();
        // 数据权限
        String dataPermission = this.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "",MmsProvinceCityMatchinfoEntity.tableName, getSessionUserBean());
        if (!StringUtil.isEmpty(dataPermission)) {
            sql.appendSingle(" and {0} ", dataPermission);
            return;
        }
        // 若是超管/省总/CFO/省级负责人则直接显示当前区域下所有区域；或者左树选择的是全国，直接返回
        if (checkIsOperators() || checkIsTop() || id.equals("0")) {
            return;
        }
        // 以下查询都是基于市级、县级权限
        // 左树点击的是一级部门则查询省级区域
        if (id.length() == 4) {
            sql.appendSingle(" and {0} = '{1}' ", MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.PROVINCE);
            // 非省总的省级负责人可看自己负责的省级区域
            if (checkIsProvinces()) {
                sql.appendSingle(" and ','||{0}||',' like '%,{1},%' ", MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                        userCode);
            } else if (checkIsCitys()) {
                // 市级权限则查询包含该用户负责的市级区域的省级区域
                sql.appendSingle(" and exists (select id from {0} m2 where {0}.id = m2.{1} and ','||m2.{2}||',' like '%,{3},%'" +
                                " and {4} = '{5}') ", MmsProvinceCityMatchinfoEntity.tableName, MmsProvinceCityMatchinfoEntity.FieldParentid,
                        MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode, userCode, MmsProvinceCityMatchinfoEntity.FieldArealevel,
                        AreaLevelEnum.CITY);
            } else if (checkIsMatchs()) {
                // 县级权限则查询包含该用户负责的县级区域的省级区域
                sql.appendSingle(" and exists (select id from {0} m2 where {0}.id = m2.{1} and {2} = '{3}' and exists " +
                                "(select id from {0} m3 where m2.id = m3.{1} and ','||m3.{4}||',' like '%,{5},%' and {2} = '{6}')) ",
                        MmsProvinceCityMatchinfoEntity.tableName, MmsProvinceCityMatchinfoEntity.FieldParentid,
                        MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.CITY, MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                        userCode, AreaLevelEnum.COUNTY);
            }
        } else {
            MmsProvinceCityMatchinfoEntity mmsProvinceCityMatchinfoEntity = this.queryById(id);
            String areaLevel = mmsProvinceCityMatchinfoEntity.getArealevel();
            // 左树点击的是省级区域则查询市级区域
            if (AreaLevelEnum.PROVINCE.equals(areaLevel)) {
                sql.appendSingle(" and {0} = '{1}' ", MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.CITY);
                if (checkIsProvinces()) {
                    return;
                } else if (checkIsCitys()) {
                    // 市级权限则查询该省级区域下此用户所有的市级区域
                    sql.appendSingle(" and ','||{0}||',' like '%,{1},%' ", MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                            userCode);
                } else if (checkIsMatchs()) {
                    // 县级权限则查询所有包含该用户负责的县级区域的市级级区域
                    sql.appendSingle(" and exists (select id from {0} m2 where {0}.id = m2.{1} and ','||m2.{2}||',' like '%,{3},%'" +
                            " and {4} = '{5}') ",  MmsProvinceCityMatchinfoEntity.tableName, MmsProvinceCityMatchinfoEntity.FieldParentid,
                            MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode, userCode, MmsProvinceCityMatchinfoEntity.FieldArealevel,
                            AreaLevelEnum.COUNTY);
                }
            } else if (AreaLevelEnum.CITY.equals(areaLevel)) {
                // 左树点击的是市级区域则查询县级区域
                sql.appendSingle(" and {0} = '{1}' ", MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.COUNTY);
                // 若当前用户为该市级区域的负责人则加载所有县级区域
                if (checkIsProvinces() || userCode.equals(mmsProvinceCityMatchinfoEntity.getAreaauthorizationusercode())) {
                    return;
                }
                // 否则加载该市级区域下当前用户负责的所有县级区域
                sql.appendSingle(" and ','||{0}||',' like '%,{1},%' ", MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                        userCode);
            }
        }
    }

    /**
     * @param
     * @description: 根据用户权限拼接sql查询区域（用于搜索条件查询）
     * @author: zhangjunyao
     * @date: 2022-03-01
     * @modify:
     */
    @Override
    public void spellSqlByUserLevelForQuery(StringBufferProxy sql) {
        String userCode = this.getSessionUserBean().getUser().getCode();
        StringBufferProxy sqlTemp = new StringBufferProxy();
        // 数据权限
        String dataPermission = this.getDataPermission(TapSystemConst.TapOperationTypeEnum.Select, "",MmsProvinceCityMatchinfoEntity.tableName, getSessionUserBean());
        if (!StringUtil.isEmpty(dataPermission)) {
            sql.appendSingle(" and {0} ", dataPermission);
            return;
        }
        // 超管查询范围无限制
        if (checkIsOperators()) {
            return;
        } else if (checkIsTop()) {// 省总、CFO可查询省内所有区域
            String deptCommonCode = mmsDeptExtraInfoService.getDeptCommonCode(this.getSessionUserBean().getDept().getCode());
            sql.appendSingle(" and {0} = '{1}' ", MmsProvinceCityMatchinfoEntity.FieldDeptcommoncode, deptCommonCode);
        } else if (checkIsProvinces()) {// 省级负责人可查询自己负责的省级区域内所有区域
            sqlTemp.appendSingle(" select id from {0} where ','||{1}||',' like '%,{2},%' and {3} = '{4}' ",
                    MmsProvinceCityMatchinfoEntity.tableName, MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                    userCode, MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.PROVINCE);
            sql.appendSingle(" and ({0} in ({1}) or {0} in (select id from {2} where {0} in ({1}))) ",
                    MmsProvinceCityMatchinfoEntity.FieldParentid, sqlTemp.toString(), MmsProvinceCityMatchinfoEntity.tableName);
        } else if (checkIsCitys()) {// 市级负责人可查询市内的区域
            sqlTemp.appendSingle(" from {0} where ','||{1}||',' like '%,{2},%' and {3} = '{4}' ",
                    MmsProvinceCityMatchinfoEntity.tableName, MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                    userCode, MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.CITY);
            sql.appendSingle(" and (id in (select id {0}) or {1} in (select id {0}) or id in (select {1} {0})) ",
                    sqlTemp.toString(), MmsProvinceCityMatchinfoEntity.FieldParentid);
        } else if (checkIsMatchs()) {// 县级负责人只可查询自己负责的县级区域
            sql.appendSingle(" and exists (select id from {0} m2 where {0}.id = m2.id and ','||m2.{1}||',' like '%,{2},%'" +
                    " and {3} = '{4}') ", MmsProvinceCityMatchinfoEntity.tableName, MmsProvinceCityMatchinfoEntity.FieldAreaauthorizationusercode,
                    userCode, MmsProvinceCityMatchinfoEntity.FieldArealevel, AreaLevelEnum.COUNTY);
        }
    }

}
